#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
销售统计控制器

提供各种销售统计API端点
"""

from fastapi import APIRouter, Query, Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from typing import Optional
from app.services.sales_statistics_service import SalesStatisticsService
from app.services.user_service import UserService

# 创建HTTP Bearer安全实例
security = HTTPBearer()

# 初始化用户服务
user_service = UserService()

async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """验证当前用户"""
    try:
        access_token = credentials.credentials
        user = user_service.verify_token(access_token)
        
        if not user:
            raise HTTPException(status_code=401, detail="无效的访问令牌")
        
        return {
            "user_id": user.get('user_id'),
            "user_no": user.get('user_no'),
            "nickname": user.get('nickname')
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=401, detail=f"令牌验证失败: {str(e)}")

# 创建路由
statistics_router = APIRouter(
    prefix="/statistics",
    tags=["statistics"],
    responses={404: {"description": "Not found"}}
)

# 创建服务实例
stats_service = SalesStatisticsService()


@statistics_router.get("/daily")
async def get_daily_sales_stats(
    date: Optional[str] = Query(None, description="日期(YYYY-MM-DD)，不传则为今天"),
    current_user = Depends(get_current_user)
):
    """获取当日销量统计"""
    try:
        result = stats_service.get_daily_sales(date)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取当日销量统计失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/weekly")
async def get_weekly_sales_stats(
    start_date: Optional[str] = Query(None, description="周起始日期(YYYY-MM-DD)，不传则为本周一"),
    current_user = Depends(get_current_user)
):
    """获取一周销量统计"""
    try:
        result = stats_service.get_weekly_sales(start_date)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取一周销量统计失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/monthly")
async def get_monthly_sales_stats(
    year_month: Optional[str] = Query(None, description="年月(YYYY-MM)，不传则为当月"),
    current_user = Depends(get_current_user)
):
    """获取一个月销量统计"""
    try:
        result = stats_service.get_monthly_sales(year_month)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取月度销量统计失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/top-products")
async def get_top_selling_products(
    period: str = Query('month', description="时间范围: today/week/month/quarter/year/all"),
    limit: int = Query(20, gt=0, le=100, description="返回商品数量"),
    current_user = Depends(get_current_user)
):
    """获取销售量最高的商品"""
    try:
        result = stats_service.get_top_selling_products(period, limit)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取热销商品排行失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/sales-curve")
async def get_sales_curve(
    period: str = Query('month', description="时间范围: week/month/quarter/year"),
    granularity: str = Query('day', description="粒度: day/week/month"),
    current_user = Depends(get_current_user)
):
    """获取销售曲线数据"""
    try:
        result = stats_service.get_sales_curve(period, granularity)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取销售曲线数据失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/comprehensive")
async def get_comprehensive_statistics(current_user = Depends(get_current_user)):
    """获取综合统计数据"""
    try:
        result = stats_service.get_comprehensive_statistics()
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取综合统计数据失败: {str(e)}",
            "data": None
        }


# 无需认证的测试接口
@statistics_router.get("/daily-test")
async def get_daily_sales_stats_test(
    date: Optional[str] = Query(None, description="日期(YYYY-MM-DD)，不传则为今天")
):
    """获取当日销量统计（测试版，无需认证）"""
    try:
        result = stats_service.get_daily_sales(date)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取当日销量统计失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/weekly-test")
async def get_weekly_sales_stats_test(
    start_date: Optional[str] = Query(None, description="周起始日期(YYYY-MM-DD)，不传则为本周一")
):
    """获取一周销量统计（测试版，无需认证）"""
    try:
        result = stats_service.get_weekly_sales(start_date)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取一周销量统计失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/top-products-test")
async def get_top_selling_products_test(
    period: str = Query('month', description="时间范围: today/week/month/quarter/year/all"),
    limit: int = Query(20, gt=0, le=100, description="返回商品数量")
):
    """获取销售量最高的商品（测试版，无需认证）"""
    try:
        result = stats_service.get_top_selling_products(period, limit)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取热销商品排行失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/sales-curve-test")
async def get_sales_curve_test(
    period: str = Query('month', description="时间范围: week/month/quarter/year"),
    granularity: str = Query('day', description="粒度: day/week/month")
):
    """获取销售曲线数据（测试版，无需认证）"""
    try:
        result = stats_service.get_sales_curve(period, granularity)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取销售曲线数据失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/monthly-test")
async def get_monthly_sales_stats_test(
    year_month: Optional[str] = Query(None, description="年月(YYYY-MM)，不传则为当月")
):
    """获取一个月销量统计（测试版，无需认证）"""
    try:
        result = stats_service.get_monthly_sales(year_month)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取月度销量统计失败: {str(e)}",
            "data": None
        }


@statistics_router.get("/comprehensive-test")
async def get_comprehensive_statistics_test():
    """获取综合统计数据（测试版，无需认证）"""
    try:
        result = stats_service.get_comprehensive_statistics()
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 400,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取综合统计数据失败: {str(e)}",
            "data": None
        } 